package com.sansui.blog.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @name: UploadFileUtil
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-07-24 23:16
 **/
//文件上传的工具类
public class UploadFileUtil {

    public static String upload(MultipartFile file) throws IOException {
        File files = new File("");
        String path = ResourceUtils.getURL("classpath:").getPath()+"static/images/tx";
        String uploadPath = path.replace('/', '\\').substring(1,path.length());

        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        };
        //获取原文件名
        String OriginalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
        //重新随机生成名字
        String filename = UUID.randomUUID().toString() +suffixName;
        //打开上传路径，拼接文件
        File localFile = new File(uploadPath+"\\"+filename);
        try {
            file.transferTo(localFile); //把上传的文件保存至本地
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("头像上传失败");
            return "";
        }
        return filename;
    }

}
